package sample.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import sample.model.Company;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class CrawlerPool extends BaseCrawler {

    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
    private ExecutorService singleThreadPool = new ThreadPoolExecutor(6, 6,0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(100), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    public CrawlerPool(String keywords, List<String> exclusiveWords, String area, Boolean filterTel, TableView<Company> qrTable, Label status)
    {
        super.keywords = keywords;
        super.area = area;
        super.qrTable = qrTable;
        super.exclusiveWords = exclusiveWords;
        super.filterTel = filterTel;
        super.status = status;
    }

    public void start(CheckBox baidu, CheckBox gaode) {
        String[] keyArr = keywords.split(" ");
        Map<String, Future> all = new HashMap<>();
        Future future = null;
        for (String key : keyArr) {
            if (baidu.isSelected()) {
                future  = singleThreadPool.submit(new BaiduCallable(key, exclusiveWords, area, filterTel, qrTable));
                all.put("百度[" + key + "]", future);
            }

            if (gaode.isSelected()) {
                future  = singleThreadPool.submit(new GaodeCallable(key, exclusiveWords, area, filterTel, qrTable));
                all.put("高德[" + key + "]", future);
            }
        }

        //Platform.runLater(new StatusUpdate(status, all));
    }

    public void stop()
    {
        //logger.info("stop()-active thread count: {}",singleThreadPool.getActiveCount());
        if(!singleThreadPool.isTerminated())
        {
            singleThreadPool.shutdownNow();
        }
        //logger.info("stop()-active thread count: {}",singleThreadPool.getActiveCount());
    }
}
